package com.example.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisCluster;

/**
 * @author shenxiang
 * @date 2020/11/14 20:28
 * @description
 */
@Component
public class StockRepository {

    @Autowired
    private JedisCluster jedisCluster;

    /**
     * 当前库存量
     */
    private static final String stockKey = "lagou:phone:stock";

    /**
     * 有效的订单列表
     */
    private static final String validOrderKey = "lagou:phone:valid:orderNo:set";

    /**
     * 已经支付过的订单列表
     */
    private static final String payedOrderKey = "lagou:phone:payed:orderNo:set";

    /**
     * 已经被取消的订单列表
     */
    private static final String cancelledOrderKey = "lagou:phone:cancelled:orderNo:set";

    // 初始库存量,因为这里只有一个商品,只需存一个值即可
    private static final Integer initStockNum = 100;

    /**
     * 初始化库存操作
     */
    private void initStock(){
        final String stockStr = jedisCluster.get(stockKey);
        if (StringUtils.isEmpty(stockStr)){
            jedisCluster.set(stockKey,initStockNum.toString());
        }
    }

    public Integer getStock(){
        Integer currentStock;
        final String stockStr = jedisCluster.get(stockKey);
        if (StringUtils.isEmpty(stockStr)){
            initStock();
            currentStock = initStockNum;
        }else{
            currentStock = Integer.parseInt(stockStr);
        }
        return currentStock;
    }

    /**
     * 减库存,每次减1
     * @return
     */
    public boolean decrStock(){
        return getStock() > 0 && jedisCluster.decr(stockKey) > 0L;
    }

    /**
     * 加库存,每次+1
     *
     * @return
     */
    public boolean incrStock(){
        return jedisCluster.incr(stockKey) > 0L;
    }

    public boolean addOrderNo(String orderNo){
        return jedisCluster.sadd(validOrderKey,orderNo) > 0L;
    }

    public boolean existsOrderNo(String orderNo){
        return jedisCluster.sismember(validOrderKey,orderNo);
    }

    public boolean delOrderNo(String orderNo){
        return jedisCluster.srem(validOrderKey,orderNo) > 0L;
    }

    public boolean addPayedOrderNo(String orderNo){
        return jedisCluster.sadd(payedOrderKey,orderNo) > 0L;
    }

    public boolean existsPayedByOrderNo(String orderNo){
        return jedisCluster.sismember(payedOrderKey,orderNo);
    }

    public boolean addCancelledOrderNo(String orderNo){
        return jedisCluster.sadd(cancelledOrderKey,orderNo) > 0L;
    }

    public boolean existsCancelledOrderNo(String orderNo){
        return jedisCluster.sismember(cancelledOrderKey,orderNo);
    }
}
